package com.laze.mywanandroid.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider

/**
 * create by Laze1
 * on 2020/7/24-10:29
 */
abstract class BaseVmFragment<VM:BaseViewModel> :Fragment() {

    protected lateinit var viewModel: VM

    abstract fun layoutRes():Int

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(layoutRes(), container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initViewModel()
        observe()
        initData()
        // 因为Fragment恢复后savedInstanceState不为null，
        // 重新恢复后会自动从ViewModel中的LiveData恢复数据，
        // 不需要重新初始化数据。
    }

    open fun observe() {}

    open fun initViewModel() {
        viewModel = ViewModelProvider(this).get(viewModelClass())
    }

    open fun initView() {}

    open fun initData() {}

    abstract fun viewModelClass(): Class<VM>

}